package com.hoshiicloud.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author yangcheng
 * @version 1.0
 * @title: SMSCodeUtil
 * @description: 短信验证码生成工具类
 * @date 2019/5/30 19:04
 * @mail maiboyc@163.com
 */
public class SMSCodeUtil {

    private static String[]  baseCode = new String[] {"0","1","2","3","4","5","6","7","8","9"};


    /**
     * 生成手机验证码,默认返回6位，可根据begin获取不同长度验证码
     * @param begin 开始位置（因为baseCode长度为10，所以如果要生成6位验证码，begin就为4，以此类推）
     * @return String
     */
    public static String code(int begin) {
        List list;
        String afterShuffle;
        String code;
        if (begin < 10) {
            list = Arrays.asList(baseCode);
            Collections.shuffle(list);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i));
            }
            afterShuffle = sb.toString();
            code = afterShuffle.substring(begin, 10);
            return code;
        } else {
            list = Arrays.asList(baseCode);
            Collections.shuffle(list);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i));
            }
            afterShuffle = sb.toString();
            code = afterShuffle.substring(-1, 10);
            return code;
        }
    }

    public static String getRandom(int num){
        if(num < 10){
            List list = Arrays.asList(baseCode);
            Collections.shuffle(list);
            List<String> x = new ArrayList<>();
            for(int i=0; i<num ;i++){
              int j=  (int)(Math.random()*10);
              x.add(list.get(j).toString());
            }
            Collections.shuffle(x);
            return StringUtils.join(x,"");
        }else{
            return "";
        }

    }
    public static void main(String args[]) {
        Set<String> hash  = new HashSet<>();
        for (int i = 0; i < 10000; i++) {
            String  s= getRandom(5);
            hash.add(s);
            System.out.println(s);
        }
        System.out.println(hash.size());
    }
}
